package com.jiepos.mpos.biz.insaccountstatement.service;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jiepos.mpos.biz.transaction.service.TransSummaryService;
import com.jiepos.mpos.biz.user.service.AppInsInfService;
import com.jiepos.mpos.common.constant.SystemConstant;
import com.jiepos.mpos.common.entity.App_Ins_InfEntity;
import com.jiepos.mpos.core.entity.Pagination;
import com.jiepos.mpos.core.service.BaseService;
import com.jiepos.mpos.core.util.CollectionUtil;
import com.jiepos.mpos.core.util.DateUtil;
import com.jiepos.mpos.core.util.PropertiesUtil;
import com.jiepos.mpos.core.util.StringUtils;

/**
 * 机构对账报表查看及下载
 * 
 * @ProjectName: [mpos1]
 * @Package com.jiepos.mpos.biz.insaccountstatement.service
 * @author 肖志伟
 * @version 1.0
 * @since 2017年11月28日 下午3:26:22
 * @history（历次修订内容、修订人、修订时间等） @UpdateRemark [说明本次修改内容]
 * @Copyright (c) 2017 江苏杰博实信息技术有限公司
 */
@Service
public class InsAccountStatementService extends BaseService {

	public final Logger log = LoggerFactory.getLogger(InsAccountStatementService.class);

	@Autowired
	private AppInsInfService appInsInfService;
	@Autowired
	private TransSummaryService transSummaryService;

	/**
	 * 获取文件列表
	 * 
	 * @param request
	 * @param pagination
	 * @param date
	 * @param end_date
	 * @return
	 */
	public Map getFileList(HttpServletRequest request, Pagination pagination, String start_date, String end_date) {
		List<File> fileList = new ArrayList<File>();
		List<String> filePathList = new ArrayList<String>();
		List<String> dateList = new ArrayList<String>();
		Map resultMap = new HashMap();
		if (StringUtils.isBlank(start_date)) {
			start_date = DateUtil.dateToStr(new Date(), "yyyyMMdd");
		} else {
			start_date = DateUtil.dateToStr(DateUtil.StringToDate(start_date), "yyyyMMdd");
		}
		if (StringUtils.isBlank(end_date)) {
			end_date = DateUtil.dateToStr(new Date(), "yyyyMMdd");
		} else {
			end_date = DateUtil.dateToStr(DateUtil.StringToDate(end_date), "yyyyMMdd");
		}
		try {
			String currentUserInsUuid = (String) request.getSession()
					.getAttribute(SystemConstant.SESSION_LOGIN_INS_UUID);
			// 形如 /0000000/1000000
			String insPath = appInsInfService.queryInsTotalRoute(currentUserInsUuid);
			App_Ins_InfEntity appInsInfEntity = appInsInfService.getInsInfByUuid(currentUserInsUuid);
			// 设置要查找的路径
			List<Date> betweensDates = getBetweenDates(DateUtil.StringToDate(start_date),
					DateUtil.StringToDate(end_date));
			for (Date date : betweensDates) {
				String hostName = PropertiesUtil.getProperty("summary.file.save.path").trim();
				hostName += (DateUtil.dateToStr(date, "yyyyMMdd") + insPath + "/");
				log.debug("查看的目录 path:" + hostName);
				// 遍历显示某个目录下的文件
				getDirFileList(hostName, fileList, filePathList, dateList, DateUtil.dateToStr(date, "yyyy-MM-dd"));
			}
			setPagination(pagination, fileList, filePathList, dateList, appInsInfEntity);
			resultMap.put("total", pagination.getMaxRowCount());
			resultMap.put("rows", pagination.getOldData());
		} catch (Exception e) {
			log.error("getDirFileList error :", e);
		} finally {
		}
		return resultMap;
	}

	/**
	 * 遍历目录下的文件
	 * 
	 * @param hostName
	 *            目录
	 * @param filePathList
	 * @param dateList
	 * @param date
	 * @param ftpFileList
	 *            文件数据
	 */
	private void getDirFileList(String hostName, List<File> fileList, List<String> filePathList, List<String> dateList,
			String date) {
		File dir = new File(hostName);
		File[] files = dir.listFiles();
		if (!CollectionUtil.isEmpty(files)) {
			for (File file : files) {
				if (!file.isDirectory()) {
					fileList.add(file);
					filePathList.add(hostName + file.getName());
					dateList.add(date);
				}
			}
		}
	}

	/**
	 * 设置分页数据
	 * 
	 * @param pagination
	 * @param filePathList
	 * @param dateList
	 * @param appInsInfEntity
	 * @param ftpFileList
	 */
	private void setPagination(Pagination pagination, List<File> fileList, List<String> filePathList,
			List<String> dateList, App_Ins_InfEntity appInsInfEntity) {
		pagination.maxRowCount = fileList.size();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		List<Object[]> dataList = new ArrayList<Object[]>();
		if (!CollectionUtil.isEmpty(fileList)) {
			Map<String, Object> map = null;
			for (int i = 0; i < fileList.size(); i++) {
				map = new HashMap<String, Object>();
				map.put("NAME", fileList.get(i).getName());
				map.put("PATH", filePathList.get(i));
				map.put("INS_CD", appInsInfEntity.getIns_cd());
				map.put("INS_NM", appInsInfEntity.getIns_cn_nm());
				map.put("DATE", dateList.get(i));
				list.add(map);
			}
			for (int i = 0; i < list.size(); i++) {
				map = list.get(i);
				Object[] obj = (Object[]) map.values().toArray();
				dataList.add(obj);
			}
		}
		pagination.setData(dataList);
		pagination.setOldData(list);
	}

	/**
	 * 
	 * @param fileName
	 *            文件名
	 * @param inputStream
	 *            输入文件流
	 * @param response
	 */
	public void downloadFile(String fileName, HttpServletResponse response, HttpServletRequest request) {
		OutputStream toClient = null;
		String hostName = PropertiesUtil.getProperty("summary.file.save.path").trim();
		log.debug("fileName===" + fileName);
		String currentUserInsUuid = (String) request.getSession().getAttribute(SystemConstant.SESSION_LOGIN_INS_UUID);
		// 形如 /0000000/1000000
		String insPath = appInsInfService.queryInsTotalRoute(currentUserInsUuid);
		// 设置要查找的路径
		log.debug("查看的目录 path:" + hostName);
		if (!new File(fileName).exists()) {
			log.debug(fileName + "文件不存在！");
			return;
		}
		try {
			File file = new File(fileName);
			InputStream inputStream = new FileInputStream(file);
			if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
				fileName = URLEncoder.encode(file.getName(), "UTF-8");
			} else {
				fileName = new String(file.getName().getBytes("UTF-8"), "ISO8859-1");
			}

			InputStream fis = new BufferedInputStream(new ByteArrayInputStream(input2byte(inputStream)));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			// 清空response
			response.reset();
			// 设置response的Header
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.setContentType("application/octet-stream; charset=utf-8");
			response.setStatus(200);
			Cookie cookie = new Cookie("fileDownload", "true");
			cookie.setPath("/");
			response.addCookie(cookie);
			// response.addHeader("Content-Length", "" + file.length());
			toClient = new BufferedOutputStream(response.getOutputStream());

			toClient.write(buffer);
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			try {
				if (toClient != null) {
					toClient.flush();
					toClient.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	public void resetReport(HttpServletRequest request, String beginDate, String endDate) {
		transSummaryService.transSummary(beginDate, endDate);
	}

	/**
	 * 输入流转化为字节数组
	 * 
	 * @param inStream
	 * @return
	 * @throws IOException
	 */
	private byte[] input2byte(InputStream inStream) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] buff = new byte[inStream.available()];
		int rc = 0;
		while ((rc = inStream.read(buff, 0, 100)) > 0) {
			baos.write(buff, 0, rc);
		}
		byte[] in2b = baos.toByteArray();
		baos.close();
		return in2b;
	}

	/**
	 * 获取两个日期之间的所有日期
	 * 
	 * @param begin
	 * @param end
	 * @return
	 */
	private List<Date> getBetweenDates(Date begin, Date end) {
		List<Date> result = new ArrayList<Date>();
		Calendar tempStart = Calendar.getInstance();
		tempStart.setTime(begin);
		while (begin.getTime() <= end.getTime()) {
			result.add(tempStart.getTime());
			tempStart.add(Calendar.DAY_OF_YEAR, 1);
			begin = tempStart.getTime();
		}
		return result;
	}

}
